package alo.p3.eg;

//循环链表
public class LinkedList {

    //头指针，哑的，第一个节点的前面，最后一个节点的后面
    private LinkedListNode head = new LinkedListNode("head", null, null);


    public LinkedList() {
        head.next = head.previous = head;
    }


    public LinkedListNode getFirst() {//获取循环链表的第一个节点
        LinkedListNode node = head.next;
        if (node == head) {
            return null;
        }
        return node;
    }


    public LinkedListNode getLast() {//获取循环链表的最后一个节点
        LinkedListNode node = head.previous;
        if (node == head) {
            return null;
        }
        return node;
    }


    public LinkedListNode addFirst(LinkedListNode node) {//将节点插入到链表的第一个位置,头节点之后.
        node.next = head.next;
        node.previous = head;
        node.previous.next = node;
        node.next.previous = node;
        return node;
    }


    public LinkedListNode addFirst(Object object) {//将值插入到链表的第一个位置,头节点之后.
        LinkedListNode node = new LinkedListNode(object, head.next, head);
        node.previous.next = node;
        node.next.previous = node;
        return node;
    }

    public LinkedListNode addLast(Object object) {//将值插入到链表的最后一个位置,头节点之前
        LinkedListNode node = new LinkedListNode(object, head, head.previous);
        node.previous.next = node;
        node.next.previous = node;
        return node;
    }


    public void clear() {//清空循环链表
        //Remove all references in the list.
        LinkedListNode node = getLast();
        while (node != null) {
            node.remove();
            node = getLast();
        }

        //Re-initialize.
        head.next = head.previous = head;
    }

    public String toString() {
        LinkedListNode node = head.next;
        StringBuffer buf = new StringBuffer();
        while (node != head) {
            buf.append(node.toString()).append(", ");
            node = node.next;
        }
        return buf.toString();
    }
}
